/**
 * @author QinGuan
 * @date:2016-1-25 下午02:29:18
 * @version :3.0
 *
 */
package com.ctvit.struts.action;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;


import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.ctvit.common.StringTrans;
import com.ctvit.wsservice.basedata.domain.*;


import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;


import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.struts2.ActionSupport;
import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.domain.Contentlog;
import com.ctvit.sms.platform.service.ContentLogService;

import com.ctvit.wsservice.basedata.domain.ChanlZoneBean;
import com.ctvit.wsservice.basedata.domain.Channelzone;
import com.ctvit.wsservice.basedata.domain.ZppmTProginfo;

@SuppressWarnings("serial")
public class ProgZoneAction extends ActionSupport {
	private static Logger logger = Logger.getLogger(ProgZoneAction.class);

	private List<Map<String, ?>> contentJson = null;// 保存结果集
	private Map<String, Object> jsonMap = null;  //保存结果集
	private ContentLogService contentService = ContextHolder
			.getBean(ContentLogService.class);// service处理类
	private HttpServletRequest request = ServletActionContext.getRequest();// 获取请求内容的上下文
	private Map chanlZone;
	private Map<String, String> updateRet;
	private String updateJson;
	private Channelzone channelzone;
	private String pgnam;

	private Map searchProg;
	private Map TFBJson;

	public static char SUCCESS = '1';
	public static char ERROR = '0';
	public static char ALERT = '2';

	/**
	 * @return
	 * @ps:获取源系统的id
	 */
	public String getSourceId() {
		contentJson = contentService.getSourceId();
		return "SourseId";
	}

	/**
	 * @return
	 * @ps:获取目标系统的id
	 */
	public String getTargetId() {
		contentJson = contentService.getTargetId();
		return "TargetId";
	}

	/**
	 * @return
	 * @ps:获取服务器名称
	 */
	public String getTargetService() {
		contentJson = contentService.getTargetService();
		return "TargetSer";
	}
	public String  getDispProgList() {
		HttpSession session=request.getSession();
		String chanlCd=request.getParameter("chanlCd");chanlZone=new HashMap();
		StringBuffer sqlBuff=new StringBuffer();
		log.info("request chanlcd="+chanlCd);
		sqlBuff.append(" SELECT f_chanl_cd,f_order,f_subj_cd,f_procode,f_prog_length,f_pgnam,f_aud_ver,f_cap_ver,f_disttime,f_is_recommend FROM (");
		sqlBuff.append(" SELECT  b.z_chanl_cd as f_chanl_cd,a.f_order,f_subj_cd,f_procode,f_subj_length as f_prog_length,f_pgnam,f_aud_ver,f_cap_ver,f_disttime,f_is_recommend,");
		sqlBuff.append(" (SELECT MAX(f_disttime) FROM t_channelzone_hist WHERE f_chanl_cd=a.f_chanl_cd) AS last_disttime");
		sqlBuff.append(" FROM zcdm_t_chanl_ex as b left join t_channelzone_hist AS a on b.z_chanl_cd=a.f_chanl_cd )AS aa");
		sqlBuff.append(" WHERE last_disttime IS NULL OR f_disttime=last_disttime");
		if (!StringUtils.isEmpty(chanlCd)) sqlBuff.append(" and f_chanl_cd='").append(chanlCd).append("'");
		sqlBuff.append(" ORDER BY f_chanl_cd,f_order ASC");
		List<Map> lst=contentService.execSql(sqlBuff.toString());
		List progList=new ArrayList();String lastChanlCd="";String loopChanlCd="";Map chanlProgMap=new HashMap();
		for (Map map : lst) {
			loopChanlCd=(String)map.get("f_chanl_cd");
			if (progList.size()>0 && !StringUtils.equals(loopChanlCd, lastChanlCd)){
				chanlProgMap=new HashMap();
				chanlProgMap.put("chanlcd", lastChanlCd);
				chanlProgMap.put("proglist", progList);
				chanlZone.put("chanlzone"+lastChanlCd, chanlProgMap);
				progList=new ArrayList();
			}else{
				if (!StringUtils.isEmpty((String)map.get("f_procode"))){
					progList.add(map);
				}else{
					progList.add(new HashMap());
				}
				lastChanlCd=loopChanlCd;
			}
		}
		chanlProgMap=new HashMap();
		chanlProgMap.put("chanlcd", lastChanlCd);
		chanlProgMap.put("proglist", progList);
		chanlZone.put("chanlzone"+lastChanlCd, chanlProgMap);
		return "progListJson";
	}
	public String  getProgList() {
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("userId");
		String disp=request.getParameter("disp");
		Channelzone channelzone=new Channelzone();
		channelzone.setChanlCd(request.getParameter("chanlGroup"));
		channelzone.setCrtuser(userId);
		if (("1").equals(disp)){
			channelzone.setDisttime(new Timestamp(System.currentTimeMillis()));
			Condition condition=new Condition();
			condition.add("crtuser", channelzone.getCrtuser());
			condition.add("chanlCd",channelzone.getChanlCd());
			contentService.updateChanlZoneProgs(channelzone, new String[]{"disttime"},condition);
		}
		String sStart=request.getParameter("start");
		String sLength=request.getParameter("length");
		if (StringUtils.isEmpty(sStart)) sStart="0";
		if (StringUtils.isEmpty(sLength)) sLength="50000";
		int start = Integer.parseInt(sStart);
		int pageSize = Integer.parseInt(sLength);
		int pageNumber = (start / pageSize) +1;
		List<ChanlZoneBean> listchanChannelzones=contentService.getChanlZoneBeansList(channelzone,pageNumber,pageSize);
		String size=contentService.getChanlZoneBeansListSize(channelzone);
		chanlZone=new HashMap();
		chanlZone.put("iTotalRecords", size);
		chanlZone.put("iTotalDisplayRecords", size);
		chanlZone.put("tableData", listchanChannelzones);
		if (listchanChannelzones!=null&&listchanChannelzones.size()>0){
			chanlZone.put("upgrade_info", listchanChannelzones.get(0));
		}
		if (("1").equals(disp)){
//			JsonConfig cfg = new JsonConfig();
//			cfg.registerJsonValueProcessor(java.sql.Timestamp.class,new DateJsonValueProcessor());
//			JSONArray jsonArray = JSONArray.fromObject(listchanChannelzones, cfg);
//			String jsonString=CommonFunc.dealWithFirstChar(jsonArray.toString());
//			CommonFunc.postJsonTo(jsonString);
		}
		return "progListJson";
	}
	public String delChanlZone(){
		String newOrd = request.getParameter("value");
		String id = request.getParameter("id");
		Channelzone channelzone=new Channelzone();
		channelzone.setId(new Long(id));
		contentService.removeChanlZoneProgs(channelzone);
		pgnam=newOrd;
		return "updateJson";
	}
	public String updateOrder(){
		String newOrd = request.getParameter("value");
		String id = request.getParameter("id");
		String[] idsStrings=id.split("_");
		String oldOrd=idsStrings[1];String chanlCd="";
		if (idsStrings.length>3){
			chanlCd=idsStrings[3];
		}
		Channelzone channelzone=new Channelzone();
		channelzone.setId(new Long(idsStrings[2]));
		channelzone.setOrder(new Long(newOrd));
		channelzone.setChanlCd(chanlCd);
		contentService.updateChanlZoneOrder(channelzone, oldOrd);
		pgnam=newOrd;
		return "updateJson";
	}
	public String updateIsRecommend(){
		String isRecommend = request.getParameter("value");
		String id = request.getParameter("id");
		Condition condition=new Condition();
		condition.add("id", id);
		Channelzone channelzone=new Channelzone();
		channelzone.setId(new Long(id));
		channelzone.setIsRecommend(isRecommend);
		contentService.updateChanlZoneProgs(channelzone, new String[]{"isRecommend"}, condition);
		return "updateJson";
	}
	public String updateReorder(){
		String newid = request.getParameter("newid");
		String oldid = request.getParameter("oldid");
		contentService.updateReorder(oldid, newid);
		return "updateJson";
	}
	public String updateHeadDesc(){
		String headDesc = request.getParameter("value");
		String id = request.getParameter("id");
		String[] idsStrings=id.split("_");
		ZppmTProginfo zppmTProginfo=new ZppmTProginfo();
		zppmTProginfo.setZProcode(idsStrings[2]);
		zppmTProginfo.setZAudVer(idsStrings[3]);
		zppmTProginfo.setZCapVer(idsStrings[4]);
		zppmTProginfo.setZProgDesc(headDesc);
		contentService.updateProgInfo(idsStrings[5], zppmTProginfo,new String[]{"zProgDesc"});
		pgnam=headDesc;
		return "updateJson";
	}
	public String updatePgname(){
		String headDesc = request.getParameter("value");
		String id = request.getParameter("id");
		String[] idsStrings=id.split("_");
		ZppmTProginfo zppmTProginfo=new ZppmTProginfo();
		zppmTProginfo.setZProcode(idsStrings[2]);
		zppmTProginfo.setZAudVer(idsStrings[3]);
		zppmTProginfo.setZCapVer(idsStrings[4]);
		zppmTProginfo.setZPgnam(headDesc);
		contentService.updateProgInfo(idsStrings[5], zppmTProginfo,new String[]{"zPgnam"});
		pgnam=headDesc;
		return "updateJson";
	}

	public String initProgList() {
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("userId");
		List chanlList = contentService.getMyChanls(userId);
		session.setAttribute("chanlGroupType", chanlList);
		return "proglist";
	}

	/**
	 * @return
	 * @ps:获取查询结果的列表
	 */
	public String getContentList() {
		Map<String, String> map = new HashMap<String, String>();
		String rows = request.getParameter("rows");// 每页显示条数
		String CurPages = request.getParameter("page");// 当前页号码
		int row = Integer.parseInt(rows);
		int CurPage = Integer.parseInt(CurPages);
		int pageSize = row == 0 ? 0 : row; // 页面显示条数
		int firstRow = (CurPage - 1) * pageSize;// 需要查询的起始行号
		map.put("zSourceSysId", request.getParameter("zSourceSysId"));
		map.put("zTargetSysId", request.getParameter("zTargetSysId"));
		map.put("zTargetService", request.getParameter("zTargetService"));
		map.put("zState", request.getParameter("zStatus"));
		map.put("beginDate", request.getParameter("beginDate"));
		map.put("endDate", request.getParameter("endDate"));
		map.put("firstRow", String.valueOf(firstRow));
		map.put("pageSize", String.valueOf(pageSize));
		List<Contentlog> list = contentService.getContentList(map);
		jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", list.size());
		jsonMap.put("rows", list);
		return "ContentList";
	}

	public String initSearchProgList() {
//		String userId = "00213030";
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("userId");
		List<ZcdmTChanl> chanlList = contentService.getChanls();

		session.setAttribute("chanlList", chanlList);

		return "searchProgList";
	}

	public String getFileProgList() {
		String str_selectDate = request.getParameter("selectDate");
		String str_progCode = request.getParameter("progCode");
		String str_progName = request.getParameter("progName");

		String sStart = request.getParameter("start");
		String sLength = request.getParameter("length");

		if (StringUtils.isEmpty(sStart)) sStart = "0";
		if (StringUtils.isEmpty(sLength)) sLength = "5";
		int start = Integer.parseInt(sStart);
		int pageSize = Integer.parseInt(sLength);
		int pageNumber = (start / pageSize);

		Map conditionMap = new HashMap();
		if (StringUtils.isNotEmpty(str_progCode)) {
			conditionMap.put("progCode", str_progCode);
		}
		if (StringUtils.isNotEmpty(str_progName)) {
			conditionMap.put("progName", str_progName);
		}
		if (StringUtils.isNotEmpty(str_selectDate)) {
			String[] dateArray = str_selectDate.split("-");
			if (dateArray.length == 2) {
				conditionMap.put("beginDate", dateArray[0]);
				conditionMap.put("endDate", dateArray[1]);
			}
		}

		List<SearchProgList> proglists = contentService.getFileProgList(conditionMap, pageNumber, pageSize);
		String size = contentService.getFileProgListSize(conditionMap);
		searchProg = new HashMap();
		searchProg.put("iTotalRecords", size);
		searchProg.put("iTotalDisplayRecords", size);
		searchProg.put("tableData", proglists);
		return "searchProgListJson";
	}
	public String getSearchProgList() {
		String str_chanlCode = request.getParameter("chanlCode");
		String str_selectDate = request.getParameter("selectDate");
		String str_subjName = request.getParameter("subjName");
		String str_progName = request.getParameter("progName");

		String sStart = request.getParameter("start");
		String sLength = request.getParameter("length");

		System.out.println(str_chanlCode);
		System.out.println(str_selectDate);
		System.out.println(str_subjName);
		System.out.println(str_progName);

		System.out.println(sStart);
		System.out.println(sLength);

		if (StringUtils.isEmpty(sStart)) sStart = "0";
		if (StringUtils.isEmpty(sLength)) sLength = "5";
		int start = Integer.parseInt(sStart);
		int pageSize = Integer.parseInt(sLength);
		int pageNumber = (start / pageSize);

		Map conditionMap = new HashMap();
		if (StringUtils.isNotEmpty(str_subjName)) {
			conditionMap.put("subjName", str_subjName);
		}
		if (StringUtils.isNotEmpty(str_progName)) {
			conditionMap.put("progName", str_progName);
		}
		if (StringUtils.isNotEmpty(str_chanlCode)) {
			if (str_chanlCode.equals("all") == false) {
				conditionMap.put("chanlCd", str_chanlCode);
			}
		}
		if (StringUtils.isNotEmpty(str_selectDate)) {
			String[] dateArray = str_selectDate.split("-");
			if (dateArray.length == 2) {
				conditionMap.put("beginDate", dateArray[0]);
				conditionMap.put("endDate", dateArray[1]);
			}
		}

		List<SearchProgList> proglists = contentService.getPageProgList(conditionMap, pageNumber, pageSize);
		String size = contentService.getSearchProgListSize(conditionMap);
		searchProg = new HashMap();
		searchProg.put("iTotalRecords", size);
		searchProg.put("iTotalDisplayRecords", size);
		searchProg.put("tableData", proglists);
		return "searchProgListJson";
	}
	public String addProgToZone() {
//		String userId = "00213030";
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("userId");
		String str_zProItemCd = request.getParameter("zProItemCd"); //节目单主键
		String str_selectedChannel = request.getParameter("selectChannel"); //主页上选择的频道
		String str_selectedOrder = request.getParameter("selectedOrder"); //主页上选择的行的序号

		Integer order;

		if (StringUtils.isEmpty(str_zProItemCd)) {
			setTFBContent(ERROR, "节目单主键为空", null);
			return "TFB";
		} else if (StringUtils.isEmpty(str_selectedChannel)) {
			setTFBContent(ERROR, "选择的频道为空", null);
			return "TFB";
		}

		if (StringUtils.isEmpty(str_selectedOrder)) {    //order为空  直接插入即可
			order = null;
		} else {
			//获取order
			try {
				order = Integer.parseInt(str_selectedOrder);
			} catch (NumberFormatException e) {
				setTFBContent(ERROR, "所选的序号不是数字", null);
				return "TFB";
			}
		}

		ZcdmTProglist proglistItem = contentService.getProugListItemByPk(str_zProItemCd);
		if (proglistItem == null) {          //未找到节目单条目
			setTFBContent(ERROR, "未找到节目单条目", null);
			return "TFB";
		}

		Boolean recordExist = contentService.checkProgInZonelist(str_selectedChannel, proglistItem.getZProcode());
		if (recordExist == null) {
			setTFBContent(ERROR, "参数有错误", null);
			return "TFB";
		} else if (recordExist == true) {     //已经存在记录了 不能添加
			setTFBContent(ERROR, "添加的节目代码已经存在", null);
			return "TFB";
		}


//		File[] fs= FileService.getFiles(CommonFunc.nasFileDir, "*" + proglistItem.getZProcode() + "*.*");
//		if(fs.length<=0){
//		//没找到文件 不保存
//			return null;
//		}
		if (order == null) {   //order为空 直接插入到最后
			contentService.insertChannelzone(str_zProItemCd, str_selectedChannel, userId);
		} else {
			contentService.insertChannelzone(str_zProItemCd, str_selectedChannel, userId, order);
		}
		setTFBContent(SUCCESS, "添加成功", null);
		return "TFB";
	}
	public String addProgToZoneByCode() {
//		String userId = "00213030";
		HttpSession session=request.getSession();
		String userId=(String)session.getAttribute("userId");
		String str_proCode = request.getParameter("proCode"); //节目代码
		String str_selectedChannel = request.getParameter("selectChannel"); //主页上选择的频道
		String str_selectedOrder = request.getParameter("selectedOrder"); //主页上选择的行的序号

		Integer order;

		if (StringUtils.isEmpty(str_proCode)) {
			setTFBContent(ERROR, "节目代码为空", null);
			return "TFB";
		} else if (StringUtils.isEmpty(str_selectedChannel)) {
			setTFBContent(ERROR, "选择的频道为空", null);
			return "TFB";
		}

		if (StringUtils.isEmpty(str_selectedOrder)) {    //order为空  直接插入即可
			order = null;
		} else {
			//获取order
			try {
				order = Integer.parseInt(str_selectedOrder);
			} catch (NumberFormatException e) {
				setTFBContent(ERROR, "所选的序号不是数字", null);
				return "TFB";
			}
		}

		Boolean recordExist = contentService.checkProgInZonelist(str_selectedChannel, str_proCode);
		if (recordExist == null) {
			setTFBContent(ERROR, "参数有错误", null);
			return "TFB";
		} else if (recordExist == true) {     //已经存在记录了 不能添加
			setTFBContent(ERROR, "添加的节目代码已经存在", null);
			return "TFB";
		}


//		File[] fs= FileService.getFiles(CommonFunc.nasFileDir, "*" + proglistItem.getZProcode() + "*.*");
//		if(fs.length<=0){
//		//没找到文件 不保存
//			return null;
//		}
		if (order == null) {   //order为空 直接插入到最后
			contentService.insertChannelzoneByProCode(str_proCode, str_selectedChannel, userId);
		} else {
			contentService.insertChannelzoneByProCode(str_proCode, str_selectedChannel, userId, order);
		}
		setTFBContent(SUCCESS, "添加成功", null);
		return "TFB";
	}

	public String initUploadProgImage() {
		HttpSession session=request.getSession();
		session.removeAttribute("errorMessage");
		session.removeAttribute("previewExists");

		String str_chanlZoneId = request.getParameter("chanlZoneId");
		String str_progCode = request.getParameter("progCode");
		String str_progName = request.getParameter("progName");
		String errorMessage = null ;

		if (StringUtils.isEmpty(str_chanlZoneId)) {
			errorMessage = "主键为空";
		} else if (StringUtils.isEmpty(str_progCode)) {
			errorMessage = "节目代码为空";
		} else if (StringUtils.isEmpty(str_progName)) {
			errorMessage = "节目名称为空";
		}
		if(errorMessage != null){    //有问题 就不执行了 直接返回错误信息
			session.setAttribute("errorMessage",errorMessage);
			return "uploadProgImage";
		}

		//找找有没有照片
		boolean previewExists = contentService.getProgPreviewExistsByChanlid(str_chanlZoneId);
		session.setAttribute("previewExists",previewExists);

		return "uploadProgImage";
	}

	public void test() {

	}

	/**
	 * 设置返回的TFB的json
	 *
	 * @param state
	 * @param message
	 * @param content
	 */
	private void setTFBContent(char state, Object message, Object content) {
		TFBJson = new HashMap();
		TFBJson.put("success", state);
		TFBJson.put("message", message);
		TFBJson.put("content", content);
	}

	public List<Map<String, ?>> getContentJson() {
		return contentJson;
	}

	public void setContentJson(List<Map<String, ?>> contentJson) {
		this.contentJson = contentJson;
	}

	public Map<String, Object> getJsonMap() {
		return jsonMap;
	}

	public void setJsonMap(Map<String, Object> jsonMap) {
		this.jsonMap = jsonMap;
	}

	public Map<String, List> getChanlZone() {
		return chanlZone;
	}

	public void setChanlZone(Map<String, List> chanlZone) {
		this.chanlZone = chanlZone;
	}

	public Map<String, String> getUpdateRet() {
		return updateRet;
	}

	public void setUpdateRet(Map<String, String> updateRet) {
		this.updateRet = updateRet;
	}

	public String getUpdateJson() {
		return updateJson;
	}

	public void setUpdateJson(String updateJson) {
		this.updateJson = updateJson;
	}

	public Channelzone getChannelzone() {
		return channelzone;
	}

	public void setChannelzone(Channelzone channelzone) {
		this.channelzone = channelzone;
	}

	public String getPgnam() {
		return pgnam;
	}

	public void setPgnam(String pgnam) {
		this.pgnam = pgnam;
	}

	public Map getSearchProg() {
		return searchProg;
	}

	public void setSearchProg(Map searchProg) {
		this.searchProg = searchProg;
	}

	public Map getTFBJson() {
		return TFBJson;
	}

	public void setTFBJson(Map TFBJson) {
		this.TFBJson = TFBJson;
	}
	@Override
	public void validate() {
		HttpSession session=request.getSession();
		session.setAttribute("userId","USIF0000000000000001");
	}
}
